from sklearn.feature_selection import r_regression
# 假设X是特征矩阵，y是目标变量
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_csv('data.csv')
X, y = data.iloc[:, :-1], data.iloc[:, -1]
#将所有null 替换为0
X = X.fillna(0)
correlation_matrix = r_regression(X, y)
# 输出相关性矩阵
correlation_matrix = np.abs(correlation_matrix)
correlation_matrix = np.around(correlation_matrix, decimals=2)


# 绘制根据大小排序后的相关性条形图，在0.5处画一条线
sorted_indices = np.argsort(correlation_matrix)
print(list(reversed(np.array(X.columns[sorted_indices]))))

plt.figure(figsize=(10, 10))
plt.barh(range(len(sorted_indices)), correlation_matrix[sorted_indices])
plt.yticks(range(len(sorted_indices)), X.columns[sorted_indices])
plt.xlabel('Correlation Coefficient')
plt.title('Feature Correlation with Target Variable')
plt.axvline(x=0.5, color='red', linestyle='--')
#plt.axvline(x=-0.5, color='red', linestyle='--')
plt.show()